<template>
    <van-nav-bar title="收货地址" left-text="" left-arrow @click-left="goBack" />

    <!-- 订单收货地址 -->
    <van-address-list v-if="action" v-model="chosenAddressId" :list="addresslist" default-tag-text="默认1" @add="onAdd"
        @edit="onEdit" @select="selectedOrder" />

    <!-- 默认收货地址 -->
    <van-address-list v-else v-model="chosenAddressId" :list="addresslist" default-tag-text="默认" @add="onAdd"
        @edit="onEdit" @select="selected" />
</template>

<script setup>
const { proxy } = getCurrentInstance()
const goBack = () => { proxy.$router.go(-1) }
const LoginUser = reactive(proxy.$cookies.get('LoginUser') ?? {})
const chosenAddressId = ref('0');
const addresslist = ref([]);
const action = proxy.$route.query.action ? proxy.$route.query.action : ''
onBeforeMount(() => {
    getAddressData();
})
const getAddressData = async () => {
    let result = await Api.AddressIndex({
        busid: LoginUser.id,
    })

    if (result.code == 1) {
        addresslist.value = [];
        result.data.forEach((item) => {
            addresslist.value.push({
                id: item.id,
                name: item.consignee,
                tel: item.mobile,
                address: item.region_text + item.address,
                isDefault: item.status == '1' ? true : false
            })

            if (item.status == '1') {
                chosenAddressId.value = item.id
            }
        })
    }
}

// 添加地址
const onAdd = () => {
    proxy.$router.push('/address/add')
};

// 编辑地址
const onEdit = (val) => {
    proxy.$router.push({
        path: '/address/edit',
        query: {
            addid: val.id
        }
    })
};;

// 切换默认地址
const selected = async (val) => {
    let result = await Api.AddressCheck({
        busid: LoginUser.id,
        addid: val.id
    })

    if (result.code == 1) {
        success(result.msg);
        getAddressData();
    }
    else {
        error(result.msg);
    }
}

const selectedOrder = (val) =>{
    proxy.$cookies.set('Address', {
        id: val.id,
        consignee: val.name,
        mobile: val.tel
    })
    goBack()
}
</script>
